package com.cswnode.demo.service.impl;

import com.cswnode.demo.dao.ChatMsgDao;
import com.cswnode.demo.dao.UserDao;
import com.cswnode.demo.entity.User;
import com.cswnode.demo.enums.YesOrNoEnum;
import com.cswnode.demo.service.UserService;
import com.cswnode.demo.util.Constant;
import com.cswnode.demo.util.Utils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2021-01-26 11:10:20
 */
@Service
public class UserServiceImpl implements UserService, Constant {
    @Autowired
    private UserDao userDao;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ChatMsgDao chatMsgDao;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Long userId) {
        return this.userDao.queryById(userId);
    }

    /**
     * 通过名字查询单条数据
     * @param username
     * @return
     */
    @Override
    public User queryByName(String username) {
        return userDao.queryByName(username);
    }

    /**
     * 通过名字查询用户是否存在
     * @param username
     * @return
     */
    @Override
    public Boolean checkExists(String username) {
        if (StringUtils.isEmpty(username)){
            return false;
        }
        return 1 == userDao.checkExists(username);
    }

    /**
     * 检查用户账号密码
     * @param username
     * @param password
     * @return
     */
    @Override
    public Boolean checkPassword(String username, String password) {
        return 1 == userDao.checkPassword(username,password);
    }

    @Override
    public Boolean checkMail(String mail) {
        if (StringUtils.isEmpty(mail)){
            return false;
        }
        return 1 == userDao.checkMail(mail);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<User> queryAllByLimit(int offset, int limit,String type,String usernameCn) {
        return this.userDao.queryAllByLimit(offset, limit,type,usernameCn);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public Map<String,Object> insert(User user) {
        Map<String, Object> msg = new HashMap<>();
        if (ObjectUtils.isEmpty(user)){
            msg.put(ERROR,"用户不能为空！");
            return msg;
        }
        user.setUserId(null);
        user.setIsDelete(YesOrNoEnum.NO.getCode());
        user.setIsActive(YesOrNoEnum.YES.getCode());
        user.setCreateTime(new Date());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCode(Utils.GetUUID().substring(0,4));
        if (checkExists(user.getUsername())){
            msg.put(ERROR,"该用户已存在！");
            return msg;
        }
        if (checkMail(user.getEmail())){
            msg.put(ERROR,"该邮箱已存在！");
            return msg;
        }
        int result = userDao.insert(user);
        if (result == 1){
            //发送信息
//            rabbitTemplate.convertAndSend("mail.Welcome",user);
            msg.put(SUCCESS,user);
            return msg;
        }
        msg.put(ERROR,"添加失败！");
        return msg;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userDao.update(user);
        return user;
    }

    @Override
    public String updateUser(User user) {
        User user1 = queryById(user.getUserId());
        if (StringUtils.isNotEmpty(user.getUsername()) &&
                !(StringUtils.equals(user.getUsername(),user1.getUsername()))){
            if (checkExists(user.getUsername())){
                return "用户名冲突，请重新输入！";
            }
        }
        if (StringUtils.isNotEmpty(user.getEmail()) &&
                !(StringUtils.equals(user.getEmail(),user1.getEmail()))){
            if (checkMail(user.getEmail())){
                return "邮箱冲突，请重新输入！";
            }
        }
        userDao.update(user);
        return null;
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long userId) {
        return this.userDao.deleteById(userId) > 0;
    }

    @Override
    public Map<String, String> updatePassword(String passwordOld, String passwordNew) {
        Map<String, String> msg = new HashMap<>();
        if (StringUtils.isEmpty(passwordOld) || StringUtils.isEmpty(passwordNew)){
            msg.put("errorMsg","密码不能为空");
            return msg;
        }
        User user = Utils.getLoginUser();
        if (user == null){
            msg.put("errorMsg","服务器异常,请联系管理员！");
            return msg;
        }
        if (!(passwordEncoder.matches(passwordOld,user.getPassword()))){
            msg.put("errorMsg","原密码输入错误！");
            return msg;
        }
        user.setPassword(passwordEncoder.encode(passwordNew));
        this.userDao.update(user);
        return null;
    }

    @Override
    public Map<String, String> updateUserNameCn(String userNameCnOld, String userNameCnNew) {
        Map<String, String> msg = new HashMap<>();
        if (StringUtils.isEmpty(userNameCnOld) || StringUtils.isEmpty(userNameCnNew)){
            msg.put("errorMsg","用户名不能为空");
            return msg;
        }
        User user = Utils.getLoginUser();
        if (user == null){
            msg.put("errorMsg","服务器异常,请联系管理员！");
            return msg;
        }
        if (!(StringUtils.equals(user.getUserNameCn(),userNameCnOld))){
            msg.put("errorMsg","原用户名输入错误！");
            return msg;
        }
        user.setUserNameCn(userNameCnNew);
        this.update(user);
        return null;
    }

    @Override
    public int selectRow(String type,String usernameCn) {
        return userDao.selectRow(type,usernameCn);
    }

    @Override
    public List<User> selectAll(String username) {
        return userDao.selectAll(Utils.getLoginUserId(),username);
    }

    @Override
    public List<User> queryChatMsg() {
        User loginUser = Utils.getLoginUser();
        List<String> userNameS = new ArrayList<>();
        List<String> from = chatMsgDao.queryFrom(loginUser.getUsername());
        List<String> to = chatMsgDao.queryTo(loginUser.getUsername());
        userNameS.addAll(from);
        userNameS.addAll(to);
        userNameS = new ArrayList(new HashSet(userNameS));
        List<User> userVos = userDao.queryChatMsg(loginUser.getUserId(), userNameS);
        return userVos;
    }
}